package com.tangyee.home.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.tangyee.MainActivity;
import com.tangyee.R;
import com.tangyee.home.activity.db.UsersInfo;
import com.tangyee.utils.CodeUtil;
import com.tangyee.utils.SessionHelper;
import com.tangyee.utils.SessionReceiver;
import com.tangyee.utils.SessionService;
import com.tangyee.utils.SessionUtil;

import org.litepal.LitePal;

import java.util.List;

public class Login extends AppCompatActivity implements View.OnClickListener, SessionHelper {
    private Button btn_login;
    private Button btn_fpwd;
    private Button btn_register;
    private List<UsersInfo> userdinfo;
    private ImageView iv_wx;
    private EditText username, password;
    private static final String TAG = "Login";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        init();
        //判断是否联网
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            Log.e(TAG, "该设备已经联网");
        } else {
            Log.e(TAG, "该设备未联网");
        }
        registerSessionReceiver();
    }

    public void init() {
        btn_login = (Button) findViewById(R.id.bn_common_login);
        btn_login.setOnClickListener(this);
        btn_fpwd = (Button) findViewById(R.id.forget_password);
        btn_fpwd.setOnClickListener(this);
        btn_register = (Button) findViewById(R.id.register);
        btn_register.setOnClickListener(this);
        iv_wx = (ImageView) findViewById(R.id.iv_weixin_login);
        iv_wx.setOnClickListener(this);
        username = (EditText) findViewById(R.id.et_username);
        password = (EditText) findViewById(R.id.et_password);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bn_common_login:
                login();
                break;
            case R.id.forget_password:
                Toast.makeText(Login.this, "你点击了忘记密码", Toast.LENGTH_SHORT).show();
                break;
            case R.id.register:
                Intent intent = new Intent(this, Register.class);
                startActivity(intent);
                finish();
                break;
            case R.id.iv_weixin_login:
                Toast.makeText(Login.this, "你点击了微信登入", Toast.LENGTH_SHORT).show();
                break;
        }
    }


    //l逻辑是先本地查询在联网查询
    public void login() {
        userdinfo = LitePal.findAll(UsersInfo.class);
        String userString = username.getText().toString().trim();
        String pwdString = password.getText().toString().trim();
        Log.e(TAG, "账号框输入的是:" + userString);
        Log.e(TAG, "密码框输入的是:" + pwdString);
        //android8.0取消了隐式广播，必须动态注册
        Intent intent = new Intent(this, SessionReceiver.class);
        intent.setAction(I_NEED_SESSIONID_BY_BROAD);
        intent.putExtra(USERNAME, userString);
        intent.putExtra(PASSWORD, pwdString);
        sendBroadcast(intent);
    }

    /**
     * 去主界面
     */
    public void gotoMainActivity() {
        Intent intent = new Intent(Login.this, MainActivity.class);
        //新建一个栈来存放被启动的activity.
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(SESSIONID, sessionid);
        intent.putExtra(JSON, jsonStr);
        intent.putExtra("preActivity", "Login.class");
        startActivity(intent);
        finish();
    }

    public void localHander(Context context, Intent intent) {
        Log.d(TAG, "状态码为:" + intent.getIntExtra(STATE, -1));
        int state = intent.getIntExtra(STATE, -1);
        if (SessionUtil.isSuccessful(state)) {
            UsersInfo usersInfo = new UsersInfo();
            usersInfo.setUsername(intent.getStringExtra(USERNAME));
            usersInfo.setStatus(1);
            usersInfo.setSessionid(intent.getStringExtra(SESSIONID));
            usersInfo.setPassword(intent.getStringExtra(PASSWORD));
            usersInfo.save();
            Log.d(TAG, usersInfo.toString());
            gotoMainActivity();
        } else {
            Toast.makeText(this, SessionUtil.getLoginHint(state), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 注册本地接受广播
     */
    @Override
    public void registerSessionReceiver() {
        sessionReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                sessionid = intent.getStringExtra(SESSIONID);
                jsonStr = intent.getStringExtra(JSON);
                Log.d(TAG, "从父类中获取的sessionid是:" + sessionid);
                Log.d(TAG, "从父类中获取的JSONSTR:" + jsonStr);
                Log.d(TAG, "接受的用户名:" + intent.getStringExtra(USERNAME));
                Log.d(TAG, "接受的密码是：" + intent.getStringExtra(PASSWORD));
                localHander(context, intent);
            }
        };
        IntentFilter filter = new IntentFilter(GET_A_SESSIONID);
        registerReceiver(sessionReceiver, filter);
    }

    @Override
    public void unregisterSessionReceiver() {
        unregisterReceiver(sessionReceiver);
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
        unregisterSessionReceiver();//注销
    }

    public BroadcastReceiver sessionReceiver = null;
    public String sessionid = null;
    public String jsonStr = null;
}
